package com.bayi.program


import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat


/**
 * @author Administrator on 2025-04-30.
 * <p>
 * 站在顶峰 看世界
 * 落到谷底 思人生
 */
class MyForegroundService : Service() {

    companion object {
        const val CHANNEL_ID = "ForegroundServiceChannel"
        const val NOTIFICATION_ID = 1
    }

    private val timeChangeReceiver = TimeChangeReceiver()
    private val replyReceiver = MyBroadcastReceiver()

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(timeChangeReceiver, intentFilter)
        // 动态注册接收器（在 Activity/Fragment 中）
        // 动态注册接收器（在 Activity/Fragment 中）
        val filter = IntentFilter("com.example.ACTION_REPLY")
        registerReceiver(replyReceiver, filter)
        ProgramListeningSingle.getInstance().startHandler()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 这里执行后台任务
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    private fun createNotification(): Notification {
        val channelId = CHANNEL_ID
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setContentTitle("后台服务运行中")
            .setContentText("正在执行后台任务...")
            .setSmallIcon(android.R.drawable.ic_menu_info_details)
            .setPriority(NotificationCompat.PRIORITY_LOW)

        return notificationBuilder.build()
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Foreground Service Channel",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "用于显示后台服务状态"
            }

            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(timeChangeReceiver)
        unregisterReceiver(replyReceiver)
    }


}